/* eslint-disable max-lines */
import React, { useCallback, useEffect, useState, useMemo } from 'react';
import { Drawer, Button, Form, Input, Tooltip, TreeSelect, Switch, Table, message } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import useOrgTreeSelect from '@/hooks/useOrgTreeSelect';
import useOrgUserTreeSelect from '@/hooks/useOrgUserTreeSelect';
import { addTag, modifyTag, getTagDetail } from '../../services';
import { ACTIONS } from '../../constants';

function isEmptyObject(obj) {
  if (typeof obj === 'object') {
    return JSON.stringify(obj) === '{}';
  }
  return false;
}

function getModeTitle(mode) {
  switch (mode) {
    case ACTIONS.ADD:
      return '添加岗位标签';
    case ACTIONS.EDIT:
      return '编辑岗位标签';
    case ACTIONS.PREVIEW:
      return '查看岗位标签';
    default:
      // 默认返回null
      console.warn(`未知模式：${mode}`);
      return null;
  }
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const TABLE_CELL_PREFIX = 'USER_LIST_UNDER_ORG_ID';

const ModifyDrawer = ({ tagId, mode, onClose, reloadParent, visible }) => {
  const [treeData, handleTreeDataLoad] = useOrgTreeSelect();
  const [userTreeData, handleOrgTreeDataLoad] = useOrgUserTreeSelect();
  // 用于详情接口加载
  const [tagDetail, setTagDetail] = useState({});
  const [selectedOrgs, setSelectedOrgs] = useState([]);
  // Table 里的 TreeSelect 使用非受控模式，性能好，依靠绑定的 rowId 根据规则生成 FieldName + setFieldValue 来更新
  const [tableData, setTableData] = useState([]);
  const [form] = Form.useForm();

  const selectedFields = useMemo(() => {
    // 会获取到所有已添加到 form 实例的 fields，包括在 form.validateFiels() 时不包含的，需要过滤
    const allFields = form.getFieldsValue(true);
    const allOrgKeys = selectedOrgs.map(org => org.orgId);
    const filteredAllFields = {};
    Object.keys(allFields).forEach((key) => {
      if (key.startsWith(TABLE_CELL_PREFIX)) {
        const realKey = Number(key.replace(`${TABLE_CELL_PREFIX}_`, ''));
        if (allOrgKeys.includes(realKey)) {
          filteredAllFields[key] = allFields[key];
        } else {
          // 清空当前已不存在的 Field 值
          form.setFieldsValue({ [key]: [] });
        }
      }
    });
    return filteredAllFields;
  }, [selectedOrgs, form]);

  useEffect(() => {
    // TODO 为过滤功能准备
    // eslint-disable-next-line no-console
    console.log(selectedFields);
  }, [selectedFields]);

  const columns = useMemo(
    () => [
      {
        title: '组织名称',
        dataIndex: 'orgName',
        key: 'orgName',
        width: '30%',
      },
      {
        title: (
          <>
            <span style={{ color: 'red', paddingLeft: 4 }}>&#42;&nbsp;</span>
            关联用户
          </>
        ),
        dataIndex: 'selectedEmployee',
        key: 'selectedEmployee',
        width: '70%',
        render: (employeeList, record) => (
          <Form.Item
            name={`${TABLE_CELL_PREFIX}_${record.orgId}`}
            initialValue={
              employeeList?.map(empolyee => ({
                label: empolyee.label,
                value: empolyee.value,
              })) || []
            }
            rules={[{ required: true }]}
          >
            <TreeSelect
              loadData={handleOrgTreeDataLoad}
              treeData={userTreeData}
              showCheckedStrategy={TreeSelect.SHOW_ALL}
              disabled={mode === ACTIONS.PREVIEW}
              placeholder="请选择组织下的人员"
              getPopupContainer={triggerNode => triggerNode.parentNode}
              virtual={false}
              treeCheckStrictly
              treeCheckable
              treeLine
              multiple
            />
          </Form.Item>
        ),
      },
    ],
    [handleOrgTreeDataLoad, mode, userTreeData],
  );

  useEffect(() => {
    async function fetchTagDetail() {
      try {
        const { code, data } = await getTagDetail(tagId);
        if (code === 0) {
          setTagDetail(data);
        } else {
          message.error('岗位标签详细信息加载失败！');
          onClose();
        }
      } catch (e) {
        onClose();
        console.error(e);
      }
    }
    if (tagId) {
      fetchTagDetail();
    }
  }, [onClose, tagId]);

  useEffect(() => {
    // 预览和编辑模式才会有默认的接口请求
    if (mode !== ACTIONS.ADD) {
      const orgs =
        tagDetail?.orgEmployeeInfo?.map(org => ({
          orgId: org.sysOrgId,
          orgName: org.orgName,
        })) || [];
      const initialTableData = orgs.map(org => ({
        ...org,
        selectedEmployee:
          tagDetail?.orgEmployeeInfo
            ?.find(o => o.sysOrgId === org.orgId)
            ?.employeeInfo?.map(employee => ({
              label: employee.employeeName,
              value: employee.sysEmployeeId,
            })) || [],
      }));
      setSelectedOrgs(orgs);
      setTableData(initialTableData);
    }
  }, [tagDetail, mode]);

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();
      try {
        const values = await form.validateFields();
        const { labelCode, labelDesc, labelName, orgId, status, ...rest } = values;
        if (mode === ACTIONS.ADD) {
          const { code, message: msg } = await addTag({
            status: status ? '1' : '0',
            labelCode,
            labelDesc,
            labelName,
            orgEmployeeRelations: orgId.map(oid => ({
              sysOrgId: oid.value,
              sysEmployeeIds: rest[`${TABLE_CELL_PREFIX}_${oid.value}`]?.map(
                employee => employee.value,
              ),
            })),
          });
          if (code === 0) {
            if (msg) {
              message.info(msg);
            }
            reloadParent();
            onClose();
          } else if (msg) {
            message.error(msg);
          }
        } else if (mode === ACTIONS.EDIT) {
          const { id } = tagDetail;
          const { code, message: msg } = await modifyTag({
            status: status ? '1' : '0',
            labelCode,
            labelDesc,
            labelName,
            id,
            orgEmployeeRelations: orgId.map(oid => ({
              sysOrgId: oid.value,
              sysEmployeeIds: rest[`${TABLE_CELL_PREFIX}_${oid.value}`]?.map(
                employee => employee.value,
              ),
            })),
          });
          if (code === 0) {
            reloadParent();
            onClose();
          } else if (msg) {
            message.error(msg);
          }
        }
        // reloadParent();
        // onClose();
      } catch (err) {
        console.error(err);
      }
    },
    [form, mode, onClose, reloadParent, tagDetail],
  );

  useEffect(() => {
    if (!visible) {
      form.resetFields(['name', 'isPrimary', 'orgId', 'dataSource', 'description']);
    }
  }, [visible, form]);

  return !isEmptyObject(tagDetail) || mode === ACTIONS.ADD ? (
    <Drawer
      title={getModeTitle(mode)}
      width={600}
      placement="right"
      onClose={onClose}
      visible={visible}
      footer={(
        <div style={{ textAlign: 'right' }}>
          <Button onClick={onClose} style={{ marginRight: 8 }}>
            取消
          </Button>
          {mode === ACTIONS.ADD && (
            <Button onClick={handleSubmit} type="primary">
              提交
            </Button>
          )}
          {mode === ACTIONS.EDIT && (
            <Button onClick={handleSubmit} type="primary">
              保存
            </Button>
          )}
        </div>
      )}
      // FIXME 这个配置不生效，visible切换的时候表单没有销毁
      destroyOnClose
    >
      <Form {...layout} form={form} name="tag-manage-form">
        <div style={{ marginBottom: 12, fontWeight: 'bold' }}>基本信息</div>
        <Form.Item
          name="labelCode"
          label={(
            <>
              <span>标签编码&nbsp;</span>
              <Tooltip title="标签管理的唯一标识">
                <InfoCircleOutlined />
              </Tooltip>
            </>
          )}
          initialValue={tagDetail?.labelCode}
          rules={[
            { required: true, message: '请输入人员组编码' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '只允许输入：字母、数字、下划线的字符串组合' },
            { max: 32, message: '字段长度不能超过 32' },
          ]}
        >
          <Input placeholder="请输入标签编码" disabled={mode !== ACTIONS.ADD} />
        </Form.Item>
        <Form.Item
          name="labelName"
          label="标签名称"
          initialValue={tagDetail?.labelName}
          rules={[
            { required: true, message: '请输入标签名称' },
            {
              pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
              message: '只允许输入：字母、数字、下划线、中文字符的字符串组合',
            },
            { max: 64, message: '字段长度不能超过 64' },
          ]}
        >
          <Input placeholder="请输入标签名称" disabled={mode === ACTIONS.PREVIEW} />
        </Form.Item>
        <Form.Item name="labelDesc" label="标签描述" initialValue={tagDetail?.labelDesc}>
          <Input.TextArea
            placeholder="请输入标签描述"
            autoSize={{ minRows: 3, maxRows: 6 }}
            disabled={mode === ACTIONS.PREVIEW}
          />
        </Form.Item>
        <Form.Item
          name="status"
          label="生效选项"
          initialValue={tagDetail?.status !== '0'}
          valuePropName="checked"
        >
          <Switch
            checkedChildren="立即生效"
            unCheckedChildren="暂不生效"
            disabled={mode === ACTIONS.PREVIEW}
          />
        </Form.Item>

        <div style={{ marginBottom: 12, fontWeight: 'bold' }}>关联部门</div>
        <Form.Item
          name="orgId"
          label="组织"
          initialValue={
            tagDetail?.orgEmployeeInfo?.map(org => ({
              label: org.orgName,
              value: org.sysOrgId,
            })) || []
          }
        >
          <TreeSelect
            loadData={handleTreeDataLoad}
            treeData={treeData}
            showCheckedStrategy={TreeSelect.SHOW_ALL}
            onChange={(selectedNodes) => {
              const nextOrgList = selectedNodes.map(({ label, value }) => ({
                orgId: value,
                orgName: label,
              }));
              const nextTableData = nextOrgList.map(org => ({ ...org, selectedEmployee: [] }));
              setSelectedOrgs(nextOrgList);
              setTableData(nextTableData);
            }}
            placeholder="请选择组织"
            getPopupContainer={triggerNode => triggerNode.parentNode}
            treeCheckStrictly
            treeCheckable
            multiple
            disabled={mode === ACTIONS.PREVIEW}
          />
        </Form.Item>

        <div style={{ marginBottom: 12, fontWeight: 'bold' }}>关联用户</div>
        <Table rowKey="orgId" columns={columns} dataSource={tableData} pagination={false} />
      </Form>
    </Drawer>
  ) : null;
};

export default ModifyDrawer;
